﻿using System;
using System.IO;
using System.Net;

namespace Ehai.Web.Framework.Rules
{
    class HtmlFromUrlRuleHandle : IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员

        public const string Name = "htmlfromurl";

        private int _execStatus = 0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }

        /// <summary>
        /// 网址html代码
        /// </summary>
        /// <param name="p">
        /// 传入数组<br />
        /// 0:(必选)处理类型,htmlfromurl<br />
        /// 1:(必选)url<br />
        /// </param>
        /// <param name="ci">环境变量</param>
        /// <example>
        /// string[] p = { "htmlfromurl", "http://www.bjfu.edu.cn"};//返回正确结果
        /// </example>
        /// <example>
        /// string[] p = { "htmlfromurl", "http://www.bjfu.edu.cnn"};//请求网址错误，抛出异常
        /// </example>
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// Ehai.Web.Framework.WebException:请求网页错误！
        /// </exception>
        /// <returns>请求网址的html代码</returns>

        public string[][] Execute(string[] p, ContextInfo ci)
        {
            string strHtml = "<BASE HREF=\"" + p[1] + "\"/>";
            string re = string.Empty;

            if (p[1] == string.Empty)
            {
#if DEBUG
                // 操作失败,状态值为1
                _execStatus = 1;
#endif
                return null;
            }

            try
            {
                StreamReader sr;

                WebRequest HttpWebRequest = WebRequest.Create(p[1]);
                WebResponse HttpWebResponse = HttpWebRequest.GetResponse();
                sr = new StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.Default);
                strHtml += sr.ReadToEnd();
                sr.Close();
#if DEBUG
                // 操作成功,状态值为0
                _execStatus = 0;
#endif
                return new string[1][] { new string[] { strHtml } };
            }

            catch (Exception ex)
            {
#if DEBUG
                // 操作失败并捕获异常,状态值为-1
                _execStatus = -1;
#endif
                throw new Ehai.Web.Framework.WebException("Ehai.WebFramework.HtmlFromUrlRule", "请求网页错误！", ex);
            }
        }

        public string GetHelpInfo()
        {
            return  "网址html代码";
        }

        public string GetHelpDetail()
        {
            return  "获得某网址的html代码:<br />" +
                    "例1: { htmlfromurl, http://www.bjfu.edu.cn/1.htm} //返回正确结果<br />" +
                    "例2: { urltohtml, http://www.bjfu.edu.cnn}" + "//请求网址错误，抛出异常<br />" +
                    "返回:请求网址的html代码";
        }

        public string[] GetParametersInfo()
        {
            string[] t = new string[2];
            t[0] = "(必选)处理类型,即\"htmlfromurl\"";
            t[1] = "(必选)url";
            return t;
        }

        #endregion
    }
}
